//
//  WHPayTools.m
//  LvZhongMagicKey
//
//  Created by 邓伟浩 on 2018/8/1.
//  Copyright © 2018年 邓伟浩. All rights reserved.
//

#import "WHPayTools.h"

#import <AlipaySDK/AlipaySDK.h> // 支付宝支付

#import "WHNetworkManager.h"
#import "WXApi.h" // 微信支付

@implementation WHPayTools

#pragma mark —————— 调起支付宝支付 ——————

+ (NSURLSessionDataTask *)alipyWithUrl:(NSString *)url parameters:(NSDictionary *)dict money:(double)money {
    return [WHNetworkManager requestWithURL:url parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (errCode.intValue == 0) {
                
                NSString *orderString = responseObject[@"retobj"];
                DLog(@"oderString: %@", orderString);
                // NOTE: 调用支付结果开始支付
                [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    
                    DLog(@"reslut = %@",resultDic);
                    [self gridResult:resultDic];
                }];
            } else {
                [WHView showMessage:errorMsg inView:nil];
            }
        } else {
            [WHView showMessage:@"支付宝返回支付数据格式错误!" inView:nil];
        }
        
    } failure:^(NSError *error) {
        [WHView showMessage:@"支付宝支付网络错误!" inView:nil];
    }];
}

+ (void)gridResult:(NSDictionary *)resultDic {
    
    NSNumber *resultStatus = resultDic[@"resultStatus"];
    
    if (resultStatus.intValue == 9000) {
        [WHView showAlertwithTitle:nil message:@"支付成功" okAction:nil cancelAction:nil];
        KPostNotification(KPayMoneySuccess, nil);
        KPostNotification(KUserInfoChange, nil);
    } else {
        [WHView showAlertwithTitle:nil message:@"支付失败" okAction:nil cancelAction:nil];
    }
    
}


#pragma mark —————— 调起微信支付 ——————

+ (NSURLSessionDataTask *)WXPayWithUrl:(NSString *)urlStr parameters:(NSDictionary *)parameters appKey:(NSString *)appid {
    return [WHNetworkManager requestWithURL:urlStr parameters:parameters isUpData:YES Success:^(id responseObject) {
        if (ValidDict(responseObject)) {
            DLog(@"%@", responseObject);
            
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (errCode.intValue == 0) {
                NSDictionary *requestDict = responseObject[@"retobj"];
                [WXApi registerApp:appid];
                [self WXPayWithDictionAry:requestDict];
            } else {
                [WHView showMessage:errorMsg inView:nil];
            }
            
        } else {
            [WHView showMessage:@"微信返回支付数据格式错误!" inView:nil];
        }
        
    } failure:^(NSError *error) {
        [WHView showMessage:@"微信支付网络错误!" inView:nil];
    }];
}

#pragma mark 微信支付方法
+ (void)WXPayWithDictionAry:(NSDictionary *)dict {
    if ([WXApi isWXAppInstalled]) {
        //需要创建这个支付对象
        PayReq *req   = [[PayReq alloc] init];
        //由用户微信号和ppID组成的唯一标识，用于校验微信用户
        req.openID = dict[@"appid"]?:@"";
        
        // 商家id，在注册的时候给的
        req.partnerId = dict[@"partnerid"]?:@"";
        
        // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
        req.prepayId  = dict[@"prepayid"]?:@"";
        
        // 根据财付通文档填写的数据和签名
        //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
        req.package   = dict[@"package"];
        
        // 随机编码，为了防止重复的，在后台生成
        req.nonceStr  = dict[@"noncestr"];
        
        // 这个是时间戳，也是在后台生成的，为了验证支付的
        NSString * stamp = dict[@"timestamp"];
        req.timeStamp = stamp.intValue;
        
        // 这个签名也是后台做的
        req.sign = dict[@"sign"];
        
        //发送请求到微信，等待微信返回onResp
        [WXApi sendReq:req];
    } else {
        [WHView showMessage:@"未安装微信!" inView:nil];
    }
    
}

@end
